﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;

namespace Vit.Common
{
    public class Unity
    {
        private static object @lock = new object();
        private static IUnityContainer unity;

        public static IUnityContainer Current
        {
            get
            {
                if (unity == null)
                {
                    lock (@lock)
                    {
                        unity = new UnityContainer();
                    }
                }
                return unity;
            }
        }

        public static IUnityContainer SetContainer(IUnityContainer container)
        {
            lock (@lock)
            {
                unity = container;
            }
            return unity;
        }
    }

    public static class UnityContainerExtensions
    {
        public static IEnumerable<T> ResolveAny<T>(this IUnityContainer unity, string name = null)
        {
            var objs = unity.ResolveAll<T>();
            try
            {
                if (unity.IsRegistered<T>(name))
                {
                    var obj = unity.Resolve<T>(name);
                    return objs.Concat(new T[] { obj });
                }
            }
            catch { }
            return objs;
        }

        public static IEnumerable<object> ResolveAny(this IUnityContainer unity, Type type, string name = null)
        {
            var objs = unity.ResolveAll(type);
            try
            {
                if (unity.IsRegistered(type, name))
                {
                    var obj = unity.Resolve(type, name);
                    return objs.Concat(new object[] { obj });
                }
            }
            catch { }
            return objs;
        }

        public static T ResolveOne<T>(this IUnityContainer unity, string name = null)
        {
            try
            {
                if (unity.IsRegistered<T>(name))
                    return unity.Resolve<T>(name);
            }
            catch { }
            return string.IsNullOrEmpty(name) ? default(T) : unity.ResolveAll<T>().FirstOrDefault();
        }

        public static object ResolveOne(this IUnityContainer unity, Type type, string name = null)
        {
            try
            {
                if (unity.IsRegistered(type, name))
                    return unity.Resolve(type, name);
            }
            catch { }
            return string.IsNullOrEmpty(name) ? null : unity.ResolveAll(type).FirstOrDefault();
        }
    }
}
